package com.design.marketPrj.application.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.design.marketPrj.application.bean.PO.User;
import com.design.marketPrj.application.service.UserService;
import com.design.marketPrj.application.util.UUIDUtils;
import com.hazelcast.util.UuidUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Controller
public class UserRegisterController {

    @Autowired
    UserService userService;

    @RequestMapping("/regist")
    public String regist(User user){
        return "register";
    }


    @RequestMapping("/registAccount")
    @ResponseBody
    public JSONObject registAccount(User user){
        JSONObject result = new JSONObject();

        if(userService.countUser(user.getUsername())>0)
        {
            result.put("code",500);
            result.put("msg","账号名重复，请换一个账号名再试");
            return result;
        }

        user.setId(UUIDUtils.getUUID());
        user.setMoney(new BigDecimal(0));
        user.setAccountType("1");
        user.setAliBind(false);

        //密码加密
        ByteSource salt = ByteSource.Util.bytes(user.getUsername());
        String newPassword = new SimpleHash("MD5",user.getPassword(),salt,1024).toHex();
        user.setPassword(newPassword);

        boolean code = userService.insert(user);
        if(code)
        {
            result.put("code",200);
            result.put("msg","注册成功!");
        }
        else
        {
            result.put("code",500);
            result.put("msg","服务器异常!");
        }
        return result;
    }



}
